const userService = require('@/services/user.service')
const JsonResult = require('@/utils/httpResponse.util')

class UserController {
  async findPage (req, response) {
    const {
      pageNo,
      pageSize,
      status,
      searchKeywords,
      nickname,
      email,
      tel,
      username,
      startTime,
      endTime
    } = req.query
    try {
      const data = await userService.findPage(pageNo, pageSize, {
        status,
        searchKeywords,
        nickname,
        email,
        tel,
        username,
        startTime,
        endTime
      })
      JsonResult.success({
        req,
        response,
        data,
        message: '查询成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '查询失败' })
    }
  }

  async updateStatus (req, response) {
    const { id, status } = req.query
    try {
      const data = await userService.updateStatus(id, status)
      if (data?.errorMessage) {
        return JsonResult.fail({ req, response, message: data.errorMessage })
      }
      JsonResult.success({
        req,
        response,
        data,
        message: '更新状态成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '更新状态失败' })
    }
  }

  async update (req, response) {
    const { id, ...attr } = req.body
    try {
      const data = await userService.updateInfo(id, attr)
      if (data?.errorMessage) {
        return JsonResult.fail({ req, response, message: data.errorMessage })
      }
      JsonResult.success({
        req,
        response,
        data,
        message: '更新成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '更新信息失败' })
    }
  }
}

module.exports = new UserController()
